package cn.good.yan.config.security;

import cn.good.yan.config.security.Filter.JwtauthencationTokenFilter;
import cn.good.yan.config.security.Filter.RestAuthorizationEntryPoint;
import cn.good.yan.config.security.Filter.RestfulAccessDeniedHandler;
import cn.good.yan.model.entity.Admin;
import cn.good.yan.model.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * Security配置类
 *
 * @author shengren.yan
 * @create 2024/9/15
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private AdminService adminService;

    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    @Autowired
    private RestAuthorizationEntryPoint restAuthorizationEntryPoint;

    // 重写 UserDetailsService ，登录逻辑
    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            Admin admin = adminService.getAdminByUserName(username);
            if (null != admin) {
                return admin;
            }
            return null;
        };
    }


    // 自己的登录逻辑
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // Security 执行我们自己重写的逻辑
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(getPw());

    }


    // 定义密码加密规则
    @Bean
    public PasswordEncoder getPw() {
        return new BCryptPasswordEncoder();
    }


    // 允许这些方法的请求,也可以在下面的 .antMatchers("/login", "/logout").permitAll() 进行处理
    // /capt  验证码接口
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/login",
                "/logout",
                "/capt",
                "/hello2",
                "/css/**",
                "/js/**",
                "/index.html",
                "favicon.ico",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/api-docs/**"

        );
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 使用JWT，不需要csrf
        http.csrf().disable()
                // 基于token ，不需要session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.authorizeRequests()
                // 允许这些方法的请求 方式1： 还可以重新 configure(WebSecurity web) 这个配置实现
//                .antMatchers("/login", "/logout").permitAll()
                // 剩下的所有请求都必须认证，登录才能访问
                .anyRequest().authenticated()
                // 可以使用 and 来区分
                .and()
                // 禁用缓存
                .headers()
                .cacheControl();

        // 添加jwt 登录拦截器
        http.addFilterBefore(jwtauthencationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        // 添加自定义未授权和未登录结果返回
        http.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthorizationEntryPoint);
    }


    // JWT 登录授权过滤器 (自定义)  进行Bean注入
    @Bean
    public JwtauthencationTokenFilter jwtauthencationTokenFilter() {
        return new JwtauthencationTokenFilter();
    }


}
